package com.movieknight;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;

// Main activity called when the application is launched. Contains tab definitions.

public class MovieKnightActivity extends Activity {
    /** Called when the activity is first created. */
	Socket server = null;
	String username = null;
	String password = null;
	TextView loginStatus = null;
	TextView session = null;
	TextView errorCode = null;
	EditText editText1 = null;
	EditText editText2 = null;
	String sessionID = null;
	boolean tabsLaunched = false;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     // These three lines will be removed when the file is actually worked on.
        /*loginStatus = (TextView) findViewById(R.id.loginStatus);        
        loginStatus.setText("");
        
        session = (TextView) findViewById(R.id.sessionID);        
        session.setText("");//Session not started
        
        errorCode = (TextView) findViewById(R.id.errorCode);        
        errorCode.setText("");*/
        
        editText1 = (EditText) findViewById(R.id.usernameBox);
        username = editText1.getText().toString();
        
        editText2 = (EditText) findViewById(R.id.passwordBox);
        password = editText2.getText().toString();
        //setContentView();
        
      //  final HomeActivity home = this;
        
        Button login = (Button) findViewById(R.id.loginButton);
        Button register = (Button) findViewById(R.id.registerButton);
       // button.setOnClickListener(new View.OnClickListener() {
       //     public void onClick(View v) {
        //        home.login();
        //    }
       // });      
        
    }
    
    public void login(View view){
    	
    	
    	//loginStatus.setText("Login Failed");
    	String st = null;
    	username = editText1.getText().toString();
    	password = editText2.getText().toString();
    	try {
    		//loginStatus.setText("Trying login..." + System.currentTimeMillis());
    		if(server == null)
    			server = new Socket("nss324-39.cse.tamu.edu",50001);
    		
    		if(server!=null)
	    		((MovieKnightApp) this.getApplication()).setServer(server);
	    	
    		Button clickedButton = (Button) view;
    		switch (clickedButton.getId())
    		   {
    		      case R.id.loginButton:
    		    	  try {
    		            	PrintWriter out = null;
    						out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);
    						out.println("{\"module\": \"auth\", \"method\": \"login_user\", \"params\": {\"username\": \"" + username + "\", \"password\": \"" + password + "\"}}");
    					} catch (IOException e1) {
    						// TODO Auto-generated catch block
    						e1.printStackTrace();
    					}  
    		          break;

    		      case R.id.registerButton:
    		    	  if(username!=null && password!=null)
    		    	  {
    		    		  try {
    		    			  PrintWriter out = null;
    		    			  out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);
    		    			  out.println("{\"module\": \"auth\", \"method\": \"register_user\", \"params\": {\"username\": \"" + username + "\", \"password\": \"" + password + "\"}}");
    		    		  } catch (IOException e1) {
    							// TODO Auto-generated catch block
    							e1.printStackTrace();
    		    		  }  
    		    	  }
    		    	  else {
    		    		  Toast.makeText(this, "Please enter a username and password to register",Toast.LENGTH_LONG).show();
    		    		  //errorCode.setText("Please enter a username and password to register");
    		    	  }
    		          break;
    		   }
	            
	            
	    		//read line(s)
	           BufferedReader input;
	           input = new BufferedReader(new InputStreamReader(server.getInputStream()));
	            
					st = input.readLine();//Get Response from Server		
					JSONObject jsonObject = null;
					
					try {
						//Parse response
						jsonObject = new JSONObject(st);
		
						//Error Codes
						int tempError = 0;
						tempError = Integer.parseInt(jsonObject.getString("error_code"));
						((MovieKnightApp) this.getApplication()).setErrorCode(tempError);		
						switch (tempError)
			    		   {
			    		      case 0:
			    		    	  //errorCode.setText("");
			    		    	  break;
			    		      case 1:

		    		    		  Toast.makeText(this, "Invalid Login",Toast.LENGTH_LONG).show();
			    		    	  //errorCode.setText("Error Code: 1 - Invalid Login");
			    		    	  break;
			    		      case 2:
			    		    	  Toast.makeText(this, "Username must be at least 4 characters long. Password must be at least 5 characters long.",Toast.LENGTH_LONG).show();
			    		    	  //errorCode.setText("Username must be at least 4 Characters\nPassword Must be at least 5 characters");
			    		    	  break;
			    		      default:
			    		    	  //errorCode.setText("Error Code: " + tempError);
			    		    	  break;
			    		   }
						
						//Session ID
						sessionID =jsonObject.getString("session_id");
						//session.setText("SessionID: " + sessionID);
						((MovieKnightApp) this.getApplication()).setSessionID(sessionID); //Set global sessionID
						((MovieKnightApp) this.getApplication()).setUsername(username); //Set global username
						
						//Log.v("sessionID", ((MovieKnightApp) this.getApplication()).getSessionID());
						
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
							 
			//Close connection
	        //  s.close();  
    	}
	    catch (UnknownHostException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	    } catch (IOException e) {
	            // TODO Auto-generated catch block
	            e.printStackTrace();
	    }
    	
    	if(server!=null)
    	{
    		if(server.isConnected()) {
    			// loginStatus.setText("Connected to Server - " + System.currentTimeMillis());
    		}
		}
    	else {
    		// loginStatus.setText("Cannot Connect to Server - " + System.currentTimeMillis());
    	}
    	
    	String tempID = ((MovieKnightApp) this.getApplication()).getSessionID();
    	if(tempID!=null && tempID!="0" && tempID!="" && tempID.length()>=20 && ((MovieKnightApp) this.getApplication()).getErrorCode()==0 && !((MovieKnightApp) this.getApplication()).isTabsLaunched())	
    	//if(sessionID!=null && sessionID!="0" && sessionID!="" && !((MovieKnightApp) this.getApplication()).isTabsLaunched())	
    	{
    		((MovieKnightApp) this.getApplication()).setTabsLaunched(true);
    		launchTabs();
    	}
    		
    }
    
    public void launchTabs()
    {
    	startActivity(new Intent(MovieKnightActivity.this, TheTabActivity.class));
    }
    
   }
